package dao

import (
	"fmt"
	"gorm.io/gorm"
	"kf/models/entity"
	"time"
)

type MessageDao struct {
	DB *gorm.DB
}

// 创建消息
func (messageDao *MessageDao) CreateMessage(kefuId string, visitorId string, content string, mesType string) {
	messageDao.DB.Exec("set names utf8mb4")
	v := &entity.Message{
		KefuId:    kefuId,
		VisitorId: visitorId,
		Content:   content,
		MesType:   mesType,
		Status:    "unread",
	}
	v.UpdatedAt = time.Now()
	messageDao.DB.Create(v)
	//将对应的客户的消息置为已读
	//如果是客户发送消息，就给客服的置为已读
	if mesType == "visitor" {
		messageDao.ReadMessageByVisitorIdAndType(visitorId, "kefu")
	} else if mesType == "kefu" {
		//如果是客服发送的消息，就给客户的置为已读
		messageDao.ReadMessageByVisitorIdAndType(visitorId, "visitor")
	}
}
func (messageDao *MessageDao) FindMessageByVisitorId(visitor_id string) []entity.Message {
	var messages []entity.Message
	messageDao.DB.Where("visitor_id=?", visitor_id).Order("id asc").Find(&messages)
	return messages
}

// 根据客户id修改消息状态
func (messageDao *MessageDao) ReadMessageByVisitorIdAndType(visitorId string, mesType string) {
	message := &entity.Message{
		Status: "read",
	}
	messageDao.DB.Model(&message).Where("visitor_id=? and mes_type=?", visitorId, mesType).Updates(message)
}

// 根据客户id修改消息状态
func (messageDao *MessageDao) ReadMessageByVisitorId(visitorId string) {
	message := &entity.Message{
		Status: "read",
	}
	messageDao.DB.Model(&message).Where("visitor_id=?", visitorId).Updates(message)
}

// 获取未读数
func (messageDao *MessageDao) FindUnreadMessageNumByVisitorId(visitor_id string) int64 {
	var count int64
	messageDao.DB.Where("visitor_id=? and status=?", visitor_id, "unread").Count(&count)
	return count
}

// 查询最后一条消息
func (messageDao *MessageDao) FindLastMessage(visitorIds []string) []entity.Message {
	var messages []entity.Message
	if len(visitorIds) <= 0 {
		return messages
	}
	var ids []entity.Message
	messageDao.DB.Select("MAX(id) id").Where(" visitor_id in (? )", visitorIds).Group("visitor_id").Find(&ids)
	if len(ids) <= 0 {
		return messages
	}
	var idStr = make([]string, 0, 0)
	for _, mes := range ids {
		idStr = append(idStr, fmt.Sprintf("%d", mes.ID))
	}
	messageDao.DB.Select("visitor_id,id,content,status,mes_type").Where(" id in (? )", idStr).Find(&messages)
	//subQuery := DB.
	//	Table("message").
	//	Where(" visitor_id in (? )", visitorIds).
	//	Order("id desc").
	//	Limit(1024).
	//	SubQuery()
	//DB.Raw("SELECT ANY_VALUE(visitor_id) visitor_id,ANY_VALUE(id) id,ANY_VALUE(content) content FROM ? message_alia GROUP BY visitor_id", subQuery).Scan(&messages)
	//DB.Select("ANY_VALUE(visitor_id) visitor_id,MAX(ANY_VALUE(id)) id,ANY_VALUE(content) content").Group("visitor_id").Find(&messages)
	return messages
}

// 查询最后一条消息
func (messageDao *MessageDao) FindLastMessageByVisitorId(visitorId string) entity.Message {
	var m entity.Message
	messageDao.DB.Select("content").Where("visitor_id=?", visitorId).Order("id desc").First(&m)
	return m
}
func (messageDao *MessageDao) FindMessageByWhere(query interface{}, args ...interface{}) []entity.MessageKefu {
	var messages []entity.MessageKefu
	messageDao.DB.Table("message").Where(query, args...).
		Select("message.*,visitor.avator visitor_avator,visitor.name visitor_name,user.avator kefu_avator,user.nickname kefu_name").
		Joins("left join sys_user on message.kefu_id=sys_user.id").
		Joins("left join visitor on visitor.visitor_id=message.visitor_id").
		Order("message.id asc").Find(&messages)
	return messages
}

// 查询条数
func (messageDao *MessageDao) CountMessage(query interface{}, args ...any) int64 {
	var count int64
	tx := messageDao.DB.Model(&entity.Message{})
	if len(args) == 0 {
		tx.Count(&count)
	} else {
		tx.Where(query, args...).Count(&count)
	}
	return count
}

func (messageDao *MessageDao) UpdateMessage(message *entity.Message) {
	messageDao.DB.Model(&entity.Message{}).Updates(message)
}

// 分页查询
func (messageDao *MessageDao) FindMessageByPage(page int, pagesize int, query any, args ...any) []*entity.MessageKefu {
	offset := (page - 1) * pagesize
	if offset < 0 {
		offset = 0
	}
	var messages []*entity.MessageKefu
	tx := messageDao.DB.Table("message").
		Select("message.*," +
			"visitor.avator visitor_avator,visitor.name visitor_name," +
			"user.avatar kefu_avator,user.nickname kefu_name").
		Offset(offset).
		Joins("left join sys_user as user on message.kefu_id=user.id").
		Joins("left join visitor on visitor.visitor_id=message.visitor_id")

	if len(args) == 0 {
		tx.Limit(pagesize).Order("message.id asc").Find(&messages)
	} else {
		tx.Where(query, args...).Limit(pagesize).Order("message.id desc").Find(&messages)
	}

	for _, mes := range messages {
		mes.CreateTime = mes.CreatedAt.Format("2006-01-02 15:04:05")
	}
	return messages
}
